//
//  NetworkTools.m
//  coca
//
//  Created by 张帅 on 15/9/27.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "NetworkTools.h"

#import <ReactiveCocoa/ReactiveCocoa.h>

#import <ReactiveCocoa/RACEXTScope.h>

#import "UserAccountViewModel.h"
@protocol NetworkToolsProxy <NSObject>

// 复制粘贴了 AFN 的内部方法
@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end


@interface NetworkTools () <NetworkToolsProxy>


@property(nonatomic,copy) NSString *clientId;

@property(nonatomic,copy)NSString * appSecret;


@end

@implementation NetworkTools



+ (instancetype)sharedTools{
    
    
    static  NetworkTools *instance=nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
    
        instance =  [[self alloc] initWithBaseURL:nil];
        // 设置反序列化的支持格式
        
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
    });
    return instance;
    
}


-(BOOL)appendTokenWithParameters:(NSMutableDictionary *)parameters{

    NSString *token  = [[UserAccountViewModel sharedUserAccount]accessToken];

    if (!token) {
        return NO;;
        
    }


    if (!parameters) {
        parameters=[NSMutableDictionary dictionary];
    }
    
    parameters[@"access_token"]=token;
    
    return YES;
    
}


-(RACSignal *)sendStatus:(NSString *)status image:(UIImage *)image{

    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
   
    params[@"status"]=status;

    
    
    if(image){
    
        return [self uploadURLString:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params image:image];
    }else
      {
          return  [self request:POST URLString:@"https://api.weibo.com/2/statuses/update.json" parameter:params withToken:YES];
    }
    
}

// MARK: - 微博数据
/// 加载微博数据
///
/// - parameter since_id:   若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
/// - parameter max_id:     若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
///
/// - returns: RAC Signal
/// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)

-(RACSignal *)loadStatussince_id:(NSInteger)since_id  max_id:(NSInteger)max_id{
    
 NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (since_id>0 ) {
       
        params[@"since_id"]= @(since_id);
        
    }else if (max_id>0){

        params[@"max_id"] =  @(max_id-1) ;
    }
    
    return  [self request:GET URLString:urlString parameter:params withToken:YES];

}


-(RACSignal *)loadUserInfoWithuid:(NSString *)uid {

    NSString* urlString = @"https://api.weibo.com/2/users/show.json";
    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"uid"]= uid;
   
    return [self request:GET URLString:urlString parameter:params withToken:YES];
    
}

-(RACSignal *)loadAccessTokenwithCode:(NSString *)code{
    
    NSString *urlString=@"https://api.weibo.com/oauth2/access_token";

   
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = self.clientId;
    params[@"client_secret"] = self.appSecret;
    params[@"grant_type"] = @"authorization_code";
    params[@"redirect_uri"] = @"http://www.baidu.com";
    params[@"code"] = code;
    
    NSLog(@"%@",params);
    
    return [self request:POST URLString:urlString parameter:params withToken:NO];
    
}



- (RACSignal *)request:(RequestMethod)method URLString:(NSString *)urlString parameter:(id)parameters withToken:(BOOL) withToken{
    
    // 根据 method 确定是 GET / POST
    NSString *methodName = (method == GET) ? @"GET": @"POST";
    
    
    __block NSMutableDictionary* parmasblock = parameters;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        
        if (withToken&&![self appendTokenWithParameters:parmasblock]) {
            
             [subscriber sendError:[NSError errorWithDomain:@ "com.itheima.error" code:-1111 userInfo:@{@"errorMessage":@"Token 为空"}]];
        }
        
 
        
        [[self dataTaskWithHTTPMethod:methodName URLString:urlString parameters:parmasblock success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
          
            [subscriber sendNext:responseObject];
            
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
           
            [subscriber sendError:error];
        }] resume];
        
        
        return nil;
    }];
    
    
}


- (NSURL *)oauthUrl{
    
    
    NSString *clientId = @"4173079140";
    
    self.clientId = clientId;
    
    NSString *appSecret = @"d2a71e9712867ed47adc472894006b95";
    
    self.appSecret = appSecret;
    
    NSString  *redirectUri = @"http://www.baidu.com";
    self.redirectUri = redirectUri;
    
    NSString  *urlString =[NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",clientId,redirectUri];
    NSURL *url = [NSURL URLWithString:urlString];
    
    return url;
    
}


// 上传文件
/// 上传文件
///
/// - parameter URLString:  URLString
/// - parameter parameters: parameters
/// - parameter image:      image
///
/// - returns: RAC Signal

-(RACSignal*)uploadURLString:(NSString*)urlString parameters:(NSMutableDictionary*)parameters image:(UIImage*)image{
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        // 0. 判断是否需要 token － 将代码放在最合适的地方

        
        if (![self appendTokenWithParameters:parameters]) {
            
            [subscriber sendError:[NSError errorWithDomain:@ "com.itheima.error" code:-10000 userInfo:@{@"errorMessage":@"Token 为空"}]];
            return nil;
        }
        
        // 1. 调用 AFN 的上传文件方法
        
        [self POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
             // 将图像转换成二进制数据
            
            NSData * data = UIImagePNGRepresentation(image);
            // formData 是遵守协议的对象，AFN内部提供的，使用的时候，只需要按照协议方法传递参数即可！
            /**
             1. 要上传图片的二进制数据
             2. 服务器的字段名，开发的时候，咨询后台
             3. 保存在服务器的文件名，很多后台允许随便写
             4. mimeType -> 客户端告诉服务器上传文件的类型，格式
             大类/小类
             image/jpg
             image/gif
             image/png
             如果，不想告诉服务器具体的类型，可以使用 application/octet-stream
             
             */
            
            [ formData appendPartWithFileData:data name:@"pic" fileName:@"ohoh" mimeType:@"application/octet-stream"];
            
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
            
            NSLog(@"%@",error);
            
            [subscriber sendError:error];
        }];
        

        return nil;
    }];
    
}


@end
